package cn.miw.android.bdmp3.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import cn.miw.android.bdmp3.model.ASong;
import cn.miw.android.bdmp3.model.BaiDuList;
import cn.miw.android.bdmp3.model.BaiDuListItem;
import cn.miw.android.bdmp3.model.Catlogs;

import com.thoughtworks.xstream.XStream;

/**
 * 百度音乐工具类
 * 
 * @author 蜜我 网站 http://apk.miw.cn 微博 http://www.weibo.com/askmiw 2012.1.15
 */
public class Util {
	private static String sessionid = "";
	public static Handler downHander = null;

	/**
	 * 解析所有分类名称
	 * 
	 * @param xml
	 * @return
	 */
	public static Catlogs parseCatalogs(String xml) {
		Catlogs catlogs = null;
		if (xml != "") {
			XStream xs = new XStream();
			xs.processAnnotations(Catlogs.class);
			catlogs = (Catlogs) xs.fromXML(xml);
		}
		return catlogs;
	}

	/**
	 * 解析一个分类
	 * 
	 * @param xml
	 * @return
	 */
	public static BaiDuList parseBaiDuList(String xml) {
		BaiDuList aBaiDuList = null;
		if (xml != "") {
			XStream xs = new XStream();
			xs.processAnnotations(BaiDuList.class);
			aBaiDuList = (BaiDuList) xs.fromXML(xml);
		}
		return aBaiDuList;
	}

	/**
	 * 解析一首歌
	 * 
	 * @param xml
	 * @return
	 */
	public static ASong parseASong(String xml) {
		ASong song = null;
		try {
			if (xml != "") {
				XStream xs = new XStream();
				xs.processAnnotations(ASong.class);
				xml = xml.replaceAll("durl>", "url>");
				song = (ASong) xs.fromXML(xml);
			}
		} catch (Exception e) {
			e.printStackTrace();
			song = null;
		}
		return song;
	}

	/**
	 * 获取网页内容
	 * 
	 * @param url
	 *            链接
	 * @param code
	 *            编码类型 gbk,utf-8
	 * @return
	 */
	public static String getWebContent(String url, String code) {
		try {
			URI uri = new URI(url.replace(" ", "%20"));
			HttpGet httpGet = new HttpGet();
			httpGet.setURI(uri);
			if (sessionid != "") {
				httpGet.setHeader("Cookie", sessionid);
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse response = httpClient.execute(httpGet);
			Header[] headers = response.getAllHeaders();
			for (int i = 0; i < headers.length; i++) {
				Header h = headers[i];
				if (h.getName().toString().equals("Set-Cookie")) {
					sessionid = h.getValue().toString();
				}
			}
			int retCode = response.getStatusLine().getStatusCode();
			if (HttpStatus.SC_OK == retCode) {
				HttpEntity entity = response.getEntity();
				return EntityUtils.toString(entity, code);
			}
		} catch (Exception e) {

		}
		return "";
	}

	/**
	 * 下载一个文件并保存
	 * 
	 * @param url
	 *            链接
	 * @param name
	 *            显示名称
	 * @param fileName
	 *            保存文件名称
	 * @param handler
	 *            接收下载进度的handler
	 */
	public static void downIt(String url, String name, String fileName, Handler handler) {
		try {
			HttpGet httpGet = new HttpGet();
			if (sessionid != "") {
				httpGet.setHeader("Cookie", sessionid);
			}
			httpGet.setURI(new URI(url));
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse response = httpClient.execute(httpGet);
			int code = response.getStatusLine().getStatusCode();
			if (HttpStatus.SC_OK == code) {
				HttpEntity entity = response.getEntity();
				int fileLenght = (int) entity.getContentLength();
				InputStream inStream = entity.getContent();
				RandomAccessFile outStream = null;
				String mDownFile = fileName;
				checkFilePath(fileName);
				int mCurPoint = 0;
				outStream = new RandomAccessFile(mDownFile, "rw");
				int result;
				byte[] data = new byte[4096];
				while ((result = inStream.read(data)) != -1) {
					outStream.seek(mCurPoint);
					outStream.write(data, 0, result);
					mCurPoint += result;
					sendMsg(handler, 1, name, mCurPoint, fileLenght);
				}
				inStream.close();
				outStream.close();
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static boolean checkFilePath(String fileName) {
		String path = fileName.substring(0,fileName.lastIndexOf(File.separator));
		File dirFile = new File(path);
		if(!dirFile.exists()){
			dirFile.mkdir();
		}
		return true;
	}

	private static void sendMsg(Handler handler, int what, Object object, int mCurPoint, int fileLenght) {
		Message msg = Message.obtain();
		msg.what = what;
		msg.obj = object;
		msg.arg1 = mCurPoint;
		msg.arg2 = fileLenght;

		if (Util.downHander != null) {
			Util.downHander.sendMessage(msg);
		}
	}

	/**
	 * 添加下载
	 * 
	 * @param ctx
	 * @param item
	 */
	public static void startDown(Context ctx, BaiDuListItem item) {
		// Dialog.setMessage("下载地址数据下载中...");
		// Dialog.show();
		int x = Util.StartDownItem(item);
		// Dialog.cancel();
		switch (x) {
		case 0:
			Toast.makeText(ctx, "添加 《" + item.getSong() + "》到下载列表！", Toast.LENGTH_SHORT).show();
			break;
		case 1:
			Toast.makeText(ctx, "下载列表中已经有《" + item.getSong() + "》", Toast.LENGTH_SHORT).show();
			break;
		case 2:
			Toast.makeText(ctx, "没有找到《" + item.getSong() + "》的有效链接。", Toast.LENGTH_SHORT).show();
			break;

		default:
			break;
		}
	}

	/**
	 * 开始下载MP3文件
	 * 
	 * @param item
	 * @return 0 添加成功 1已经存在 2链接无效
	 */
	public static int StartDownItem(BaiDuListItem item) {
		ASong aSong = getASong(item);
		if ((aSong != null) && (aSong.getTrueURL() != "")) {
			String url = aSong.getTrueURL();
			String name = item.getSinger() + "-" + item.getSong();
			BaiDuListItem x = Pub.downListMap.get(name);
			if (x == null) {
				Pub.downListMap.put(name, item);
				String filename = Pub.SavePath + File.separator + item.getSinger() + "-" + item.getSong() + ".mp3";
				new AnsyncDownTask(url, name, filename, downHander).execute();
				return 0;
			} else {
				return 1;
			}
		}
		return 2;
	}

	/**
	 * 下载歌词
	 * 
	 * @param item
	 * @return
	 */
	public static boolean StartDownLRC(BaiDuListItem item) {
		ASong aSong = getASong(item);
		if (aSong != null) {
			if (aSong.getLrcURL() != "") {
				String name = item.getSinger() + "-" + item.getSong();
				String filename = Pub.SavePath + File.separator + item.getSinger() + "-" + item.getSong() + ".lrc";
				new AnsyncDownTask(aSong.getLrcURL(), name, filename, downHander).execute();
				return true;
			}
		}
		return false;
	}

	/**
	 * 根据item，获取歌曲的描述信息，包含音乐文件、歌词文件等下载地址
	 * 
	 * @param item
	 * @return
	 */
	public static ASong getASong(BaiDuListItem item) {
		String url = "http://box.zhangmen.baidu.com/x?op=12&count=1&mtype=2&url=&listenreelect=0&title=";
		url += item.getName();
		String xml = Util.getWebContent(url, "gbk");
		ASong aSong = null;
		if (xml != "") {
			aSong = parseASong(xml);
		}
		return aSong;
	}

	/**
	 * 删除广告目录
	 * 
	 * @param path
	 */
	public static void DelAD(String path) {
		try {
			File file = new File(path);
			if (file.isDirectory()) {
				File[] sub = file.listFiles();
				for (File file2 : sub) {
					DelAD(file2.getAbsolutePath());
				}
				file.delete();
			} else {
				file.delete();
				System.out.println(path + " deleted.");
			}
		} catch (Exception e) {
			System.out.println(path + "删除失败。");
		}
	}
}
